<?php !defined('BASE_ROOT') && exit ( 'Access Denied!' );
class CAI_Controller extends Basic{

	/**
	 * 模板和缓存对象
	 *
	 * @var Template
	 */
	private $templateDir;
	protected $cache;
	private $value;
	private $_parent_name;

	/**
	 * 构造函数.
	 *
	 * @return void
	 * @access public
	 *
	 */
	public function __construct() {
		$this->_assign_libraries();
		$this->_parent_name = ucfirst(get_class($this));
		$this->templateDir = BASE_ROOT . DS . APP_DIR . DS . 'views' . DS;
		$this->cache = $this->plugin('Cache');
	}

	/**
	 * 调用全局的变量
	 */
	private function _assign_libraries()
	{
		$CAI =& get_instance();
		foreach (array_keys(get_object_vars($CAI)) as $key)
		{
			if ( ! isset($this->$key) && $key != $this->_parent_name)
			{
				$this->$key = NULL; // Needed to prevent reference errors with some configurations
				$this->$key =& $CAI->$key;
			}
		}
	}

	/**
	 * 设置模板变量
	 *
	 * @param string $key   模板页面变量
	 * @param mixed $value  对应程序中的变量
	 * @access public
	 * @return void
	 */
	final public function assign() {
		$key = @func_get_arg(0);
		$value = @func_get_arg(1);
		if (is_array($key)) {
			$this->assignByArray($key);
		} else {
			$this->value[$key] = $value;
		}
	}
	/**
	 * 通过数组分配变量
	 *
	 * @param array $array
	 */
	private function assignByArray($array) {
		if (is_array($array)) {
			foreach ($array as $k => $v) {
				$this->value[$k] = $v;
			}
		}
	}

	/**
	 * 显示模板
	 *
	 * @param string $tpl  模板文件名 为空时就和类(Action)名相同
	 * @access public
	 * @return void
	 */
	final public function show($tpl = null) {
		$tpl_file = $this->templateDir . $tpl;
		if (is_file($tpl_file)) {
			@extract($this->value);
			include($tpl_file);
		} else {
			show_error('找不到模板文件:' . $tpl_file);
		}
	}

	/**
	 * 获取脚本执行时间
	 *
	 * @return float
	 * @access public
	 */
	final public function getRunTime() {
		global $START_TIME;
		return microtime(true) - $START_TIME;
	}
}